package Utils;

import java.io.BufferedReader;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
/**
 * @author lvthang
 *
 */
public class Download {
	/**
	 * @param url1
	 * @param outPut
	 * 
	 * @description download file with method get
	 */
	
	public static String reload(String url1) {
		BufferedReader rd=null;
		String res="";
		try {
			URL url = new URL(url1);
			URLConnection conn = url.openConnection();
			conn.setConnectTimeout(10*1000);
			rd = new BufferedReader(new InputStreamReader(conn
					.getInputStream(), "UTF-8"));

			String line = "";

			while ((line = rd.readLine()) != null) {
				res+=line;
			}
		} catch (Exception e){
			//System.out.println("Server index: Error download at "+(new Date()).toString());
		}finally {
			try {
				if (rd!=null) rd.close();
			} catch (IOException e) {
			}
		}
		return res;


	}
	public static String download(String link,String folder, String filename){
		OutputStream out = null;
		URLConnection conn = null;
		InputStream  in = null;
		String filetype = "";
		try {
			URL url = new URL(link.replace(" ", "%20"));
			String host=link.replace("http://", "");
			host=host.substring(0, host.indexOf("/")).split("\\:")[0];
			
			
			conn = url.openConnection();
			conn.setConnectTimeout(1000*60*2);
			conn.setReadTimeout(1000*60*2);
			conn.setRequestProperty("Host", host);
			filetype = conn.getContentType();
			

			if(filetype.toLowerCase().indexOf("jpeg")>=0)
				filetype = ".jpg";
			else if(filetype.toLowerCase().indexOf("jpg")>=0)
				filetype = ".jpg";
			else if(filetype.toLowerCase().indexOf("gif")>=0)
				filetype = ".gif";
			else if(filetype.toLowerCase().indexOf("png")>=0)
				filetype = ".png";
			else filetype = "";
			out = new BufferedOutputStream(
					new FileOutputStream(folder+"/"+filename+filetype));
			
			in = conn.getInputStream();
			byte[] buffer = new byte[4*1024];
			int numRead;
			while ((numRead = in.read(buffer)) != -1) {
				out.write(buffer, 0, numRead);
			}
		} catch (Exception exception) {
			exception.printStackTrace();
			System.out.println("khong tim thay file "+link);
			return "";
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (IOException ioe) {
			}
		}
		return filename + filetype;
	}
	public static boolean downloadGet(String url1, String outPut) {
		BufferedReader rd=null;
		BufferedWriter wr1=null;
		try {
			URL url = new URL(url1);
			URLConnection conn = url.openConnection();
			conn.setReadTimeout(60*1000*4);
			rd = new BufferedReader(new InputStreamReader(conn
					.getInputStream(), "UTF-8"));

			String line = "";
			wr1 = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(outPut), "UTF-8"));
			while ((line = rd.readLine()) != null) {
				wr1.write(line);
			}
			return true;
		} catch (MalformedURLException e) {
		} catch (UnsupportedEncodingException e) {
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("<===========Link die============>");
		} finally {
			try {
				if (wr1!=null) wr1.close();
				if (rd!=null) rd.close();
			} catch (IOException e) {
			}
		}
		return false;
	}
	
	public static final Document parseDom(String url,String tempFile){
		try {
			Download.downloadGet(url, tempFile);
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory
					.newDocumentBuilder();
			return docBuilder.parse(new File(tempFile));
		} catch (Exception e) {
			return null;
		}
	}
	public static void main(String[] args) {
		Download.download("http://img2.news.zing.vn/2012/06/02/mb2.jpg", "D:/", "text.jpg");
	}
}
